<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>sql优化 | 逆流时光~</title><meta name="keywords" content="SQL"><meta name="author" content="FantasticCode,1443996278@qq.com"><meta name="copyright" content="FantasticCode"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1. 查询SQL尽量不要使用select *，而是select具体字段 反例：  select * from employee;  正例：  select id，name from employee;  原因：只取需要的字段，节省资源、减少网络开销； ​		   select * 进行查询时，很可能就不会使用到覆盖索引了，就会造成回表查询。 2. 如果知道查询结果只有一条或者只要最大&#x2F;最小一条记录">
<meta property="og:type" content="article">
<meta property="og:title" content="sql优化">
<meta property="og:url" content="https://yyj_challenged.gitee.io/2020/12/15/sql%E4%BC%98%E5%8C%96/index.html">
<meta property="og:site_name" content="逆流时光~">
<meta property="og:description" content="1. 查询SQL尽量不要使用select *，而是select具体字段 反例：  select * from employee;  正例：  select id，name from employee;  原因：只取需要的字段，节省资源、减少网络开销； ​		   select * 进行查询时，很可能就不会使用到覆盖索引了，就会造成回表查询。 2. 如果知道查询结果只有一条或者只要最大&#x2F;最小一条记录">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg13.jpg">
<meta property="article:published_time" content="2020-12-14T16:00:00.000Z">
<meta property="article:modified_time" content="2022-05-30T07:08:52.740Z">
<meta property="article:author" content="FantasticCode">
<meta property="article:tag" content="SQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg13.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://yyj_challenged.gitee.io/2020/12/15/sql%E4%BC%98%E5%8C%96/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/img/pwa/manifest.json"/><link rel="apple-touch-icon" sizes="180x180" href="/img/pwa/apple-touch-icon.png"/><link rel="icon" type="image/png" sizes="32x32" href="/img/pwa/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/img/pwa/16.png"/><link rel="mask-icon" href="/img/pwa/safari-pinned-tab.svg" color="#5bbad5"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?67fada177b615329655b957d30519c62";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"UVE3L335VP","apiKey":"5c662b130a966e23356d9dd1739405cd","indexName":"dev_myblog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: FantasticCode","link":"链接: ","source":"来源: 逆流时光~","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'sql优化',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-30 15:08:52'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/atom.xml" title="逆流时光~" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">20</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">32</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E9%9F%B3%E4%B9%90"><i class="fa-fw /music/"></i><span> 0</span></a></li><li><a class="site-page child" href="/%E5%9B%BE%E7%89%87"><i class="fa-fw /picture/"></i><span> 1</span></a></li><li><a class="site-page child" href="/%E7%94%B5%E5%BD%B1"><i class="fa-fw /movie/"></i><span> 2</span></a></li><li><a class="site-page child" href="/%E4%B9%A6%E7%B1%8D"><i class="fa-fw /books/"></i><span> 3</span></a></li><li><a class="site-page child" href="/%E6%B8%B8%E6%88%8F"><i class="fa-fw /game/"></i><span> 4</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/treasure/"><i class="fa-fw fas fa-link"></i><span> 宝藏</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg13.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">逆流时光~</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E9%9F%B3%E4%B9%90"><i class="fa-fw /music/"></i><span> 0</span></a></li><li><a class="site-page child" href="/%E5%9B%BE%E7%89%87"><i class="fa-fw /picture/"></i><span> 1</span></a></li><li><a class="site-page child" href="/%E7%94%B5%E5%BD%B1"><i class="fa-fw /movie/"></i><span> 2</span></a></li><li><a class="site-page child" href="/%E4%B9%A6%E7%B1%8D"><i class="fa-fw /books/"></i><span> 3</span></a></li><li><a class="site-page child" href="/%E6%B8%B8%E6%88%8F"><i class="fa-fw /game/"></i><span> 4</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/treasure/"><i class="fa-fw fas fa-link"></i><span> 宝藏</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">sql优化</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-12-14T16:00:00.000Z" title="发表于 2020-12-15 00:00:00">2020-12-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-30T07:08:52.740Z" title="更新于 2022-05-30 15:08:52">2022-05-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Develop/">Develop</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>14分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="sql优化"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h5 id="1-查询SQL尽量不要使用select-，而是select具体字段">1. 查询SQL尽量不要使用select *，而是select具体字段</h5>
<p>反例：</p>
<blockquote>
<p>select * from employee;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>select id，name from employee;</p>
</blockquote>
<p>原因：只取需要的字段，节省资源、减少网络开销；</p>
<p>​		   select * 进行查询时，很可能就不会使用到覆盖索引了，就会造成回表查询。</p>
<h5 id="2-如果知道查询结果只有一条或者只要最大-最小一条记录，建议用limit-1">2. 如果知道查询结果只有一条或者只要最大/最小一条记录，建议用limit 1</h5>
<p>现状：假设现在有employee员工表，要找出一个名字叫jack的人.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE `employee` (</span><br><span class="line">  `id` int(11) NOT NULL,</span><br><span class="line">  `name` varchar(255) DEFAULT NULL,</span><br><span class="line">  `age` int(11) DEFAULT NULL,</span><br><span class="line">  `date` datetime DEFAULT NULL,</span><br><span class="line">  `sex` int(1) DEFAULT NULL,</span><br><span class="line">  PRIMARY KEY (`id`)</span><br><span class="line">) ENGINE=InnoDB DEFAULT CHARSET=utf8;</span><br></pre></td></tr></table></figure>
<p>反例：</p>
<blockquote>
<p>select id，name from employee where name=‘jack’</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>select id，name from employee where name=‘jack’ limit 1;</p>
</blockquote>
<p>理由：</p>
<ul>
<li>加上limit 1后,只要找到了对应的一条记录,就不会继续向下扫描了,效率将会大大提高。</li>
<li>当然，如果name是唯一索引的话，是不必要加上limit 1了，因为limit的存在主要就是为了防止全表扫描，从而提高性能,如果一个语句本身可以预知不用全表扫描，有没有limit ，性能的差别并不大。</li>
</ul>
<h5 id="3-应尽量避免在where子句中使用or来连接条件">3. 应尽量避免在where子句中使用or来连接条件</h5>
<p>新建一个user表，它有一个普通索引userId，表结构如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE `user` (</span><br><span class="line">  `id` int(11) NOT NULL AUTO_INCREMENT,</span><br><span class="line">  `userId` int(11) NOT NULL,</span><br><span class="line">  `age` int(11) NOT NULL,</span><br><span class="line">  `name` varchar(255) NOT NULL,</span><br><span class="line">  PRIMARY KEY (`id`),</span><br><span class="line">  KEY `idx_userId` (`userId`)</span><br><span class="line">) ENGINE=InnoDB DEFAULT CHARSET=utf8;</span><br></pre></td></tr></table></figure>
<p>查询userid为1或者年龄为18岁的用户</p>
<p>反例：</p>
<blockquote>
<p>select * from user where userid=1 or age =18</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>//使用union all<br>
select * from user where userid=1<br>
union all<br>
select * from user where age = 18</p>
<p>//或者分开两条sql写：<br>
select * from user where userid=1<br>
select * from user where age = 18</p>
</blockquote>
<p>理由：使用or可能会使索引失效，从而全表扫描。对于or+没有索引的age这种情况，假设它走了userId的索引，但是走到age查询条件时，它还得全表扫描，也就是需要三步过程：全表扫描+索引扫描+合并 如果它一开始就走全表扫描，直接一遍扫描就完事。mysql是有优化器的，处于效率与成本考虑，遇到or条件，索引可能失效，看起来也合情合理。</p>
<h5 id="4-优化limit分页">4. 优化limit分页</h5>
<p>我们日常做分页需求时，一般会用 limit 实现，但是当偏移量特别大的时候，查询效率就变得低下。</p>
<p>反例：</p>
<blockquote>
<p>select id，name，age from employee limit 10000，10</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>//方案一 ：返回上次查询的最大记录(偏移量)<br>
select id，name from employee where id&gt;10000 limit 10.</p>
<p>//方案二：order by + 索引<br>
select id，name from employee order by id  limit 10000，10</p>
<p>//方案三：在业务允许的情况下限制页数：</p>
</blockquote>
<p>理由：</p>
<ul>
<li>当偏移量最大的时候，查询效率就会越低，因为Mysql并非是跳过偏移量直接去取后面的数据，而是先把偏移量+要取的条数，然后再把前面偏移量这一段的数据抛弃掉再返回的。</li>
<li>如果使用优化方案一，返回上次最大查询记录（偏移量），这样可以跳过偏移量，效率提升不少。</li>
<li>方案二使用order by+索引，也是可以提高查询效率的。</li>
<li>方案三的话，建议跟业务讨论，有没有必要查这么后的分页啦。因为绝大多数用户都不会往后翻太多页。</li>
</ul>
<h5 id="5-优化你的like语句">5. 优化你的like语句</h5>
<p>日常开发中，如果用到模糊关键字查询，很容易想到like，但是like很可能让你的索引失效。</p>
<p>反例(把%放前面，并不走索引)：</p>
<blockquote>
<p>select userId，name from user where userId like ‘%123’;</p>
</blockquote>
<p>正例(把%放关键字后面，还是会走索引的)：</p>
<blockquote>
<p>select userId，name from user where userId like ‘123%’;</p>
</blockquote>
<h5 id="6-使用where条件限定要查询的数据，避免返回多余的行">6. 使用where条件限定要查询的数据，避免返回多余的行</h5>
<p>假设业务场景是这样：查询某个用户是否是会员</p>
<p>反例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Long&gt; userIds = sqlMap.queryList(<span class="string">&quot;select userId from user where isVip=1&quot;</span>);</span><br><span class="line"><span class="type">boolean</span> <span class="variable">isVip</span> <span class="operator">=</span> userIds.contains(userId);</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Long</span> <span class="variable">userId</span> <span class="operator">=</span> sqlMap.queryObject(<span class="string">&quot;select userId from user where userId=&#x27;userId&#x27; and isVip=&#x27;1&#x27; &quot;</span>)</span><br><span class="line"><span class="type">boolean</span> <span class="variable">isVip</span> <span class="operator">=</span> userId！=<span class="literal">null</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>需要什么数据，就去查什么数据，避免返回不必要的数据，节省开销。</li>
</ul>
<h5 id="7-尽量避免在索引列上使用mysql的内置函数">7. 尽量避免在索引列上使用mysql的内置函数</h5>
<p>业务需求：查询最近七天内登陆过的用户(假设loginTime加了索引)</p>
<p>反例：索引列上使用mysql的内置函数，索引失效</p>
<blockquote>
<p>select userId,loginTime from loginuser where Date_ADD(loginTime,Interval 7 DAY) &gt;=now();</p>
</blockquote>
<p>正例：如果索引列不加内置函数，索引还是会走的</p>
<blockquote>
<p>explain  select userId,loginTime from loginuser where  loginTime &gt;= Date_ADD(NOW(),INTERVAL - 7 DAY);</p>
</blockquote>
<h5 id="8-应尽量避免在-where-子句中对字段进行表达式操作，这将导致系统放弃使用索引而进行全表扫">8. 应尽量避免在 where 子句中对字段进行表达式操作，这将导致系统放弃使用索引而进行全表扫</h5>
<p>反例：</p>
<blockquote>
<p>select * from user where age-1 =10；</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>select * from user where age =11；</p>
</blockquote>
<h5 id="9-Inner-join-、left-join、right-join，优先使用Inner-join，如果是left-join，左边表结果尽量小">9. Inner join 、left join、right join，优先使用Inner join，如果是left join，左边表结果尽量小</h5>
<ul>
<li>Inner join 内连接，在两张表进行连接查询时，只保留两张表中完全匹配的结果集</li>
<li>left join 在两张表进行连接查询时，会返回左表所有的行，即使在右表中没有匹配的记录。</li>
<li>right join 在两张表进行连接查询时，会返回右表所有的行，即使在左表中没有匹配的记录。</li>
</ul>
<p>都满足SQL需求的前提下，推荐优先使用Inner join（内连接），如果要使用left join，左边表数据结果尽量小，如果有条件的尽量放到左边处理。</p>
<p>反例：</p>
<blockquote>
<p>select * from tab1 t1 left join tab2 t2  on t1.size = t2.size where <a target="_blank" rel="noopener" href="http://t1.id">t1.id</a>&gt;2;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>select * from (select * from tab1 where id &gt;2) t1 left join tab2 t2 on t1.size = t2.size;</p>
</blockquote>
<p>理由：</p>
<ul>
<li>如果inner join是等值连接，或许返回的行数比较少，所以性能相对会好一点。</li>
<li>同理，使用了左连接，左边表数据结果尽量小，条件尽量放到左边处理，意味着返回的行数可能比较少。</li>
</ul>
<h5 id="10-应尽量避免在-where-子句中使用-或-操作符，否则将引擎放弃使用索引而进行全表扫描">10. 应尽量避免在 where 子句中使用!=或&lt;&gt;操作符，否则将引擎放弃使用索引而进行全表扫描</h5>
<p>反例：</p>
<blockquote>
<p>select age,name  from user where age &lt;&gt;18;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p><em>//可以考虑分开两条sql写</em><br>
select age,name  from user where age &lt;18;<br>
select age,name  from user where age &gt;18;</p>
</blockquote>
<h5 id="11-使用联合索引时，注意索引列的顺序，一般遵循最左匹配原则">11. 使用联合索引时，注意索引列的顺序，一般遵循最左匹配原则</h5>
<p>表结构：（有一个联合索引idx_userid_age，userId在前，age在后）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE `user` (</span><br><span class="line">  `id` int(11) NOT NULL AUTO_INCREMENT,</span><br><span class="line">  `userId` int(11) NOT NULL,</span><br><span class="line">  `age` int(11) DEFAULT NULL,</span><br><span class="line">  `name` varchar(255) NOT NULL,</span><br><span class="line">  PRIMARY KEY (`id`),</span><br><span class="line">  KEY `idx_userid_age` (`userId`,`age`) USING BTREE</span><br><span class="line">) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;</span><br></pre></td></tr></table></figure>
<p>反例：</p>
<blockquote>
<p>select * from user where age = 10;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p><em>//符合最左匹配原则</em><br>
select * from user where userid=10 and age =10；<br>
<em>//符合最左匹配原则</em><br>
select * from user where userid =10;</p>
</blockquote>
<ul>
<li>当我们创建一个联合索引的时候，如(k1,k2,k3)，相当于创建了（k1）、(k1,k2)和(k1,k2,k3)三个索引，这就是最左匹配原则。</li>
<li>联合索引不满足最左原则，索引一般会失效，但是这个还跟Mysql优化器有关的。</li>
</ul>
<h5 id="12-对查询进行优化，应考虑在-where-及-order-by-涉及的列上建立索引，尽量避免全表扫描">12. 对查询进行优化，应考虑在 where 及 order by 涉及的列上建立索引，尽量避免全表扫描</h5>
<p>反例：</p>
<blockquote>
<p>select * from user where address =‘深圳’ order by age ;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>添加索引<br>
alter table user add index idx_address_age (address,age)</p>
</blockquote>
<h5 id="13-如果插入数据过多，考虑批量插入。">13. 如果插入数据过多，考虑批量插入。</h5>
<p>反例：</p>
<blockquote>
<p>for(User u :list){<br>
INSERT into user(name,age) values(#name#,#age#)<br>
}</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p><em>//一次500批量插入，分批进行</em><br>
insert into user(name,age) values<br>
<foreach collection="list" item="item" index="index" separator=","><br>
(#{<a target="_blank" rel="noopener" href="http://item.name">item.name</a>},#{item.age})<br>
</foreach></p>
</blockquote>
<h5 id="14-在适当的时候，使用覆盖索引">14. 在适当的时候，使用覆盖索引</h5>
<p>覆盖索引能够使得你的SQL语句不需要回表，仅仅访问索引就能够得到所有需要的数据，大大提高了查询效率。</p>
<p>反例：</p>
<blockquote>
<p><em>// like模糊查询，不走索引了</em><br>
select * from user where userid like ‘%123%’;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p><em>//id为主键，那么为普通索引，即覆盖索引登场了。</em><br>
select id,name from user where userid like ‘%123%’;</p>
</blockquote>
<h5 id="15-慎用distinct关键字">15. 慎用distinct关键字</h5>
<p>distinct 关键字一般用来过滤重复记录，以返回不重复的记录。在查询一个字段或者很少字段的情况下使用时，给查询带来优化效果。但是在字段很多的时候使用，却会大大降低查询效率。</p>
<p>反例：</p>
<blockquote>
<p>select DISTINCT * from  user;</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>select DISTINCT name from user;</p>
</blockquote>
<p>带distinct的语句cpu时间和占用时间都高于不带distinct的语句。因为当查询很多字段时，如果使用distinct，数据库引擎就会对数据进行比较，过滤掉重复数据，然而这个比较，过滤的过程会占用系统资源，cpu时间。</p>
<h5 id="16-删除冗余和重复索引">16. 删除冗余和重复索引</h5>
<p>反例：</p>
<blockquote>
<p>KEY <code>idx_userId</code> (<code>userId</code>)<br>
KEY <code>idx_userId_age</code> (<code>userId</code>,<code>age</code>)</p>
</blockquote>
<p>正例：</p>
<blockquote>
<p>KEY <code>idx_userId</code> (<code>userId</code>)<br>
KEY <code>idx_userId_age</code> (<code>userId</code>,<code>age</code>)</p>
</blockquote>
<p>重复的索引需要维护，并且优化器在优化查询的时候也需要逐个地进行考虑，这会影响性能的.</p>
<h5 id="17-如果数据量较大，优化你的修改-删除语句。">17. 如果数据量较大，优化你的修改/删除语句。</h5>
<p>避免同时修改或删除过多数据，因为会造成cpu利用率过高，从而影响别人对数据库的访问。一次性删除太多数据，可能会有lock wait timeout exceed的错误，所以建议分批操作。</p>
<h5 id="18-where子句中考虑使用默认值代替null">18. where子句中考虑使用默认值代替null</h5>
<ul>
<li>并不是说使用了is null 或者 is not null 就会不走索引了，这个跟mysql版本以及查询成本都有关。如果mysql优化器发现，走索引比不走索引成本还要高，肯定会放弃索引，这些条件<code>！=，&gt;is null，is not null</code>经常被认为让索引失效，其实是因为一般情况下，查询的成本高，优化器自动放弃的。</li>
<li>如果把null值，换成默认值，很多时候让走索引成为可能，同时，表达意思会相对清晰一点。</li>
</ul>
<h5 id="19-不要有超过5个以上的表连接">19. 不要有超过5个以上的表连接</h5>
<ul>
<li>连表越多，编译的时间和开销也就越大。</li>
<li>把连接表拆开成较小的几个执行，可读性更高。</li>
<li>如果一定需要连接很多表才能得到数据，那么意味着糟糕的设计了。</li>
</ul>
<h5 id="20-exist-in的合理利用">20. exist &amp; in的合理利用</h5>
<p>假设表A表示某企业的员工表，表B表示部门表，查询所有部门的所有员工，很容易有以下SQL:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from A where deptId in (select deptId from B);</span><br></pre></td></tr></table></figure>
<p>这样写等价于：</p>
<blockquote>
<p>先查询部门表B</p>
<p>select deptId from B</p>
<p>再由部门deptId，查询A的员工</p>
<p>select * from A where A.deptId = B.deptId</p>
</blockquote>
<p>可以抽象成这样的一个循环：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">List&lt;&gt; resultSet ;</span><br><span class="line"> for(int i=0;i&lt;B.length;i++) &#123;</span><br><span class="line">       for(int j=0;j&lt;A.length;j++) &#123;</span><br><span class="line">       if(A[i].id==B[j].id) &#123;</span><br><span class="line">          resultSet.add(A[i]);</span><br><span class="line">          break;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>显然，除了使用in，我们也可以用exists实现一样的查询功能，如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from A where exists (select 1 from B where A.deptId = B.deptId);</span><br></pre></td></tr></table></figure>
<p>因为exists查询的理解就是，先执行主查询，获得数据后，再放到子查询中做条件验证，根据验证结果（true或者false），来决定主查询的数据结果是否得意保留。</p>
<p>那么，这样写就等价于：</p>
<blockquote>
<p>select * from A,先从A表做循环</p>
<p>select * from B where A.deptId = B.deptId,再从B表做循环.</p>
</blockquote>
<p>同理，可以抽象成这样一个循环：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">List&lt;&gt; resultSet ;</span><br><span class="line"> for(int i=0;i&lt;A.length;i++) &#123;</span><br><span class="line">       for(int j=0;j&lt;B.length;j++) &#123;</span><br><span class="line">       if(A[i].deptId==B[j].deptId) &#123;</span><br><span class="line">          resultSet.add(A[i]);</span><br><span class="line">          break;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>数据库最费劲的就是跟程序链接释放。假设链接了两次，每次做上百万次的数据集查询，查完就走，这样就只做了两次；相反建立了上百万次链接，申请链接释放反复重复，这样系统就受不了了。即mysql优化原则，就是小表驱动大表，小的数据集驱动大的数据集，从而让性能更优。</p>
<p>因此，我们要选择最外层循环小的，也就是，如果<strong>B的数据量小于A，适合使用in，如果B的数据量大于A，即适合选择exist</strong>。</p>
<h5 id="21、尽量用-union-all-替换-union">21、尽量用 union all 替换 union</h5>
<p>如果检索结果中不会有重复的记录，推荐union all 替换 union。</p>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">select * from user where userid=1 </span><br><span class="line">union</span><br><span class="line">select * from user where age = 10</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">select * from user where userid=1 </span><br><span class="line">union all</span><br><span class="line">select * from user where age = 10</span><br></pre></td></tr></table></figure>
<p>理由：</p>
<ul>
<li>如果使用union，不管检索结果有没有重复，都会尝试进行合并，然后在输出最终结果前进行排序。如果已知检索结果没有重复记录，使用union all 代替union，这样会提高效率。</li>
</ul>
<h5 id="22、索引不宜太多，一般5个以内。">22、索引不宜太多，一般5个以内。</h5>
<ul>
<li>索引并不是越多越好，索引虽然提高了查询的效率，但是也降低了插入和更新的效率。</li>
<li>insert或update时有可能会重建索引，所以建索引需要慎重考虑，视具体情况来定。</li>
<li>一个表的索引数最好不要超过5个，若太多需要考虑一些索引是否没有存在的必要。</li>
</ul>
<h5 id="23、尽量使用数字型字段，若只含数值信息的字段尽量不要设计为字符型">23、尽量使用数字型字段，若只含数值信息的字段尽量不要设计为字符型</h5>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">king_id` varchar（20） NOT NULL COMMENT &#x27;守护者Id&#x27;</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`king_id` int(11) NOT NULL COMMENT &#x27;守护者Id&#x27;`</span><br></pre></td></tr></table></figure>
<p>理由：</p>
<ul>
<li>相对于数字型字段，字符型会降低查询和连接的性能，并会增加存储开销。</li>
</ul>
<h5 id="24、索引不适合建在有大量重复数据的字段上，如性别这类型数据库字段。">24、索引不适合建在有大量重复数据的字段上，如性别这类型数据库字段。</h5>
<p>因为SQL优化器是根据表中数据量来进行查询优化的，如果索引列有大量重复数据，Mysql查询优化器推算发现不走索引的成本更低，很可能就放弃索引了。</p>
<h5 id="25、尽量避免向客户端返回过多数据量。">25、尽量避免向客户端返回过多数据量。</h5>
<p>假设业务需求是，用户请求查看自己最近一年观看过的直播数据。</p>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//一次性查询所有数据回来</span><br><span class="line">select * from LivingInfo where watchId =useId and watchTime &gt;= Date_sub(now(),Interval 1 Y)</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">//分页查询</span><br><span class="line">select * from LivingInfo where watchId =useId and watchTime&gt;= Date_sub(now(),Interval 1 Y) limit offset，pageSize</span><br><span class="line"></span><br><span class="line">//如果是前端分页，可以先查询前两百条记录，因为一般用户应该也不会往下翻太多页，</span><br><span class="line">select * from LivingInfo where watchId =useId and watchTime&gt;= Date_sub(now(),Interval 1 Y) limit 200 ;</span><br></pre></td></tr></table></figure>
<h5 id="26、当在SQL语句中连接多个表时-请使用表的别名，并把别名前缀于每一列上，这样语义更加清晰。">26、当在SQL语句中连接多个表时,请使用表的别名，并把别名前缀于每一列上，这样语义更加清晰。</h5>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">select  * from A inner</span><br><span class="line">join B on A.deptId = B.deptId;</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">select  memeber.name,deptment.deptName from A member inner</span><br><span class="line">join B deptment on member.deptId = deptment.deptId;</span><br></pre></td></tr></table></figure>
<h5 id="27、尽可能使用varchar-nvarchar-代替-char-nchar。">27、尽可能使用varchar/nvarchar 代替 char/nchar。</h5>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`deptName` char(100) DEFAULT NULL COMMENT &#x27;部门名称&#x27;</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`deptName` varchar(100) DEFAULT NULL COMMENT &#x27;部门名称&#x27;</span><br></pre></td></tr></table></figure>
<p>理由：</p>
<ul>
<li>因为首先变长字段存储空间小，可以节省存储空间。</li>
<li>其次对于查询来说，在一个相对较小的字段内搜索，效率更高。</li>
</ul>
<h5 id="28、为了提高group-by-语句的效率，可以在执行到该语句前，把不需要的记录过滤掉。">28、为了提高group by 语句的效率，可以在执行到该语句前，把不需要的记录过滤掉。</h5>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">select job，avg（salary） from employee  group by job having job =&#x27;president&#x27; </span><br><span class="line">or job = &#x27;managent&#x27;</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">select job，avg（salary） from employee where job =&#x27;president&#x27; </span><br><span class="line">or job = &#x27;managent&#x27; group by job；</span><br></pre></td></tr></table></figure>
<h5 id="29、如何字段类型是字符串，where时一定用引号括起来，否则索引失效">29、如何字段类型是字符串，where时一定用引号括起来，否则索引失效</h5>
<p>反例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from user where userid =123;</span><br></pre></td></tr></table></figure>
<p>正例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from user where userid =&#x27;123&#x27;;</span><br></pre></td></tr></table></figure>
<p>理由：</p>
<ul>
<li>为什么第一条语句未加单引号就不走索引了呢？这是因为不加单引号时，是字符串跟数字的比较，它们类型不匹配，MySQL会做隐式的类型转换，把它们转换为浮点数再做比较。</li>
</ul>
<h5 id="30、使用explain-分析你SQL的计划">30、使用explain 分析你SQL的计划</h5>
<p>日常开发写SQL的时候，尽量养成一个习惯吧。用explain分析一下你写的SQL，尤其是走不走索引这一块。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://yyj_challenged.gitee.io">FantasticCode</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yyj_challenged.gitee.io/2020/12/15/sql%E4%BC%98%E5%8C%96/">https://yyj_challenged.gitee.io/2020/12/15/sql%E4%BC%98%E5%8C%96/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yyj_challenged.gitee.io" target="_blank">逆流时光~</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/SQL/">SQL</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg13.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/gh/overtrue/share.js@master/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/12/15/sql%E5%9F%BA%E7%A1%80/"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg14.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">sql基础</div></div></a></div><div class="next-post pull-right"><a href="/2020/12/15/log4j2%E6%95%B4%E7%90%86/"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg15.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">log日志框架对比</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/12/15/sql%E5%9F%BA%E7%A1%80/" title="sql基础"><img class="cover" src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg14.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-15</div><div class="title">sql基础</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">FantasticCode</div><div class="author-info__description">铅华洗尽,一缕芳华</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">20</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">32</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/FantasticCode2019" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://leetcode.cn/u/fantastic_code2018" target="_blank" title="leetcode"><i class="fa-duotone fa-code"></i></a><a class="social-icon" href="mailto:1443996278Yao@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/168589693" target="_blank" title="bilibili"><i class="fa-brands fa-bilibili"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36662611" target="_blank" title="CSDN"><i class="fa-solid fa-c"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E6%9F%A5%E8%AF%A2SQL%E5%B0%BD%E9%87%8F%E4%B8%8D%E8%A6%81%E4%BD%BF%E7%94%A8select-%EF%BC%8C%E8%80%8C%E6%98%AFselect%E5%85%B7%E4%BD%93%E5%AD%97%E6%AE%B5"><span class="toc-number">1.</span> <span class="toc-text">1. 查询SQL尽量不要使用select *，而是select具体字段</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E5%A6%82%E6%9E%9C%E7%9F%A5%E9%81%93%E6%9F%A5%E8%AF%A2%E7%BB%93%E6%9E%9C%E5%8F%AA%E6%9C%89%E4%B8%80%E6%9D%A1%E6%88%96%E8%80%85%E5%8F%AA%E8%A6%81%E6%9C%80%E5%A4%A7-%E6%9C%80%E5%B0%8F%E4%B8%80%E6%9D%A1%E8%AE%B0%E5%BD%95%EF%BC%8C%E5%BB%BA%E8%AE%AE%E7%94%A8limit-1"><span class="toc-number">2.</span> <span class="toc-text">2. 如果知道查询结果只有一条或者只要最大&#x2F;最小一条记录，建议用limit 1</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E5%BA%94%E5%B0%BD%E9%87%8F%E9%81%BF%E5%85%8D%E5%9C%A8where%E5%AD%90%E5%8F%A5%E4%B8%AD%E4%BD%BF%E7%94%A8or%E6%9D%A5%E8%BF%9E%E6%8E%A5%E6%9D%A1%E4%BB%B6"><span class="toc-number">3.</span> <span class="toc-text">3. 应尽量避免在where子句中使用or来连接条件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4-%E4%BC%98%E5%8C%96limit%E5%88%86%E9%A1%B5"><span class="toc-number">4.</span> <span class="toc-text">4. 优化limit分页</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5-%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84like%E8%AF%AD%E5%8F%A5"><span class="toc-number">5.</span> <span class="toc-text">5. 优化你的like语句</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#6-%E4%BD%BF%E7%94%A8where%E6%9D%A1%E4%BB%B6%E9%99%90%E5%AE%9A%E8%A6%81%E6%9F%A5%E8%AF%A2%E7%9A%84%E6%95%B0%E6%8D%AE%EF%BC%8C%E9%81%BF%E5%85%8D%E8%BF%94%E5%9B%9E%E5%A4%9A%E4%BD%99%E7%9A%84%E8%A1%8C"><span class="toc-number">6.</span> <span class="toc-text">6. 使用where条件限定要查询的数据，避免返回多余的行</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#7-%E5%B0%BD%E9%87%8F%E9%81%BF%E5%85%8D%E5%9C%A8%E7%B4%A2%E5%BC%95%E5%88%97%E4%B8%8A%E4%BD%BF%E7%94%A8mysql%E7%9A%84%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0"><span class="toc-number">7.</span> <span class="toc-text">7. 尽量避免在索引列上使用mysql的内置函数</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#8-%E5%BA%94%E5%B0%BD%E9%87%8F%E9%81%BF%E5%85%8D%E5%9C%A8-where-%E5%AD%90%E5%8F%A5%E4%B8%AD%E5%AF%B9%E5%AD%97%E6%AE%B5%E8%BF%9B%E8%A1%8C%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%93%8D%E4%BD%9C%EF%BC%8C%E8%BF%99%E5%B0%86%E5%AF%BC%E8%87%B4%E7%B3%BB%E7%BB%9F%E6%94%BE%E5%BC%83%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95%E8%80%8C%E8%BF%9B%E8%A1%8C%E5%85%A8%E8%A1%A8%E6%89%AB"><span class="toc-number">8.</span> <span class="toc-text">8. 应尽量避免在 where 子句中对字段进行表达式操作，这将导致系统放弃使用索引而进行全表扫</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#9-Inner-join-%E3%80%81left-join%E3%80%81right-join%EF%BC%8C%E4%BC%98%E5%85%88%E4%BD%BF%E7%94%A8Inner-join%EF%BC%8C%E5%A6%82%E6%9E%9C%E6%98%AFleft-join%EF%BC%8C%E5%B7%A6%E8%BE%B9%E8%A1%A8%E7%BB%93%E6%9E%9C%E5%B0%BD%E9%87%8F%E5%B0%8F"><span class="toc-number">9.</span> <span class="toc-text">9. Inner join 、left join、right join，优先使用Inner join，如果是left join，左边表结果尽量小</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#10-%E5%BA%94%E5%B0%BD%E9%87%8F%E9%81%BF%E5%85%8D%E5%9C%A8-where-%E5%AD%90%E5%8F%A5%E4%B8%AD%E4%BD%BF%E7%94%A8-%E6%88%96-%E6%93%8D%E4%BD%9C%E7%AC%A6%EF%BC%8C%E5%90%A6%E5%88%99%E5%B0%86%E5%BC%95%E6%93%8E%E6%94%BE%E5%BC%83%E4%BD%BF%E7%94%A8%E7%B4%A2%E5%BC%95%E8%80%8C%E8%BF%9B%E8%A1%8C%E5%85%A8%E8%A1%A8%E6%89%AB%E6%8F%8F"><span class="toc-number">10.</span> <span class="toc-text">10. 应尽量避免在 where 子句中使用!&#x3D;或&lt;&gt;操作符，否则将引擎放弃使用索引而进行全表扫描</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#11-%E4%BD%BF%E7%94%A8%E8%81%94%E5%90%88%E7%B4%A2%E5%BC%95%E6%97%B6%EF%BC%8C%E6%B3%A8%E6%84%8F%E7%B4%A2%E5%BC%95%E5%88%97%E7%9A%84%E9%A1%BA%E5%BA%8F%EF%BC%8C%E4%B8%80%E8%88%AC%E9%81%B5%E5%BE%AA%E6%9C%80%E5%B7%A6%E5%8C%B9%E9%85%8D%E5%8E%9F%E5%88%99"><span class="toc-number">11.</span> <span class="toc-text">11. 使用联合索引时，注意索引列的顺序，一般遵循最左匹配原则</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#12-%E5%AF%B9%E6%9F%A5%E8%AF%A2%E8%BF%9B%E8%A1%8C%E4%BC%98%E5%8C%96%EF%BC%8C%E5%BA%94%E8%80%83%E8%99%91%E5%9C%A8-where-%E5%8F%8A-order-by-%E6%B6%89%E5%8F%8A%E7%9A%84%E5%88%97%E4%B8%8A%E5%BB%BA%E7%AB%8B%E7%B4%A2%E5%BC%95%EF%BC%8C%E5%B0%BD%E9%87%8F%E9%81%BF%E5%85%8D%E5%85%A8%E8%A1%A8%E6%89%AB%E6%8F%8F"><span class="toc-number">12.</span> <span class="toc-text">12. 对查询进行优化，应考虑在 where 及 order by 涉及的列上建立索引，尽量避免全表扫描</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#13-%E5%A6%82%E6%9E%9C%E6%8F%92%E5%85%A5%E6%95%B0%E6%8D%AE%E8%BF%87%E5%A4%9A%EF%BC%8C%E8%80%83%E8%99%91%E6%89%B9%E9%87%8F%E6%8F%92%E5%85%A5%E3%80%82"><span class="toc-number">13.</span> <span class="toc-text">13. 如果插入数据过多，考虑批量插入。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#14-%E5%9C%A8%E9%80%82%E5%BD%93%E7%9A%84%E6%97%B6%E5%80%99%EF%BC%8C%E4%BD%BF%E7%94%A8%E8%A6%86%E7%9B%96%E7%B4%A2%E5%BC%95"><span class="toc-number">14.</span> <span class="toc-text">14. 在适当的时候，使用覆盖索引</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#15-%E6%85%8E%E7%94%A8distinct%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-number">15.</span> <span class="toc-text">15. 慎用distinct关键字</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#16-%E5%88%A0%E9%99%A4%E5%86%97%E4%BD%99%E5%92%8C%E9%87%8D%E5%A4%8D%E7%B4%A2%E5%BC%95"><span class="toc-number">16.</span> <span class="toc-text">16. 删除冗余和重复索引</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#17-%E5%A6%82%E6%9E%9C%E6%95%B0%E6%8D%AE%E9%87%8F%E8%BE%83%E5%A4%A7%EF%BC%8C%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84%E4%BF%AE%E6%94%B9-%E5%88%A0%E9%99%A4%E8%AF%AD%E5%8F%A5%E3%80%82"><span class="toc-number">17.</span> <span class="toc-text">17. 如果数据量较大，优化你的修改&#x2F;删除语句。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#18-where%E5%AD%90%E5%8F%A5%E4%B8%AD%E8%80%83%E8%99%91%E4%BD%BF%E7%94%A8%E9%BB%98%E8%AE%A4%E5%80%BC%E4%BB%A3%E6%9B%BFnull"><span class="toc-number">18.</span> <span class="toc-text">18. where子句中考虑使用默认值代替null</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#19-%E4%B8%8D%E8%A6%81%E6%9C%89%E8%B6%85%E8%BF%875%E4%B8%AA%E4%BB%A5%E4%B8%8A%E7%9A%84%E8%A1%A8%E8%BF%9E%E6%8E%A5"><span class="toc-number">19.</span> <span class="toc-text">19. 不要有超过5个以上的表连接</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#20-exist-in%E7%9A%84%E5%90%88%E7%90%86%E5%88%A9%E7%94%A8"><span class="toc-number">20.</span> <span class="toc-text">20. exist &amp; in的合理利用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#21%E3%80%81%E5%B0%BD%E9%87%8F%E7%94%A8-union-all-%E6%9B%BF%E6%8D%A2-union"><span class="toc-number">21.</span> <span class="toc-text">21、尽量用 union all 替换 union</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#22%E3%80%81%E7%B4%A2%E5%BC%95%E4%B8%8D%E5%AE%9C%E5%A4%AA%E5%A4%9A%EF%BC%8C%E4%B8%80%E8%88%AC5%E4%B8%AA%E4%BB%A5%E5%86%85%E3%80%82"><span class="toc-number">22.</span> <span class="toc-text">22、索引不宜太多，一般5个以内。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#23%E3%80%81%E5%B0%BD%E9%87%8F%E4%BD%BF%E7%94%A8%E6%95%B0%E5%AD%97%E5%9E%8B%E5%AD%97%E6%AE%B5%EF%BC%8C%E8%8B%A5%E5%8F%AA%E5%90%AB%E6%95%B0%E5%80%BC%E4%BF%A1%E6%81%AF%E7%9A%84%E5%AD%97%E6%AE%B5%E5%B0%BD%E9%87%8F%E4%B8%8D%E8%A6%81%E8%AE%BE%E8%AE%A1%E4%B8%BA%E5%AD%97%E7%AC%A6%E5%9E%8B"><span class="toc-number">23.</span> <span class="toc-text">23、尽量使用数字型字段，若只含数值信息的字段尽量不要设计为字符型</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#24%E3%80%81%E7%B4%A2%E5%BC%95%E4%B8%8D%E9%80%82%E5%90%88%E5%BB%BA%E5%9C%A8%E6%9C%89%E5%A4%A7%E9%87%8F%E9%87%8D%E5%A4%8D%E6%95%B0%E6%8D%AE%E7%9A%84%E5%AD%97%E6%AE%B5%E4%B8%8A%EF%BC%8C%E5%A6%82%E6%80%A7%E5%88%AB%E8%BF%99%E7%B1%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AD%97%E6%AE%B5%E3%80%82"><span class="toc-number">24.</span> <span class="toc-text">24、索引不适合建在有大量重复数据的字段上，如性别这类型数据库字段。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#25%E3%80%81%E5%B0%BD%E9%87%8F%E9%81%BF%E5%85%8D%E5%90%91%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%BF%94%E5%9B%9E%E8%BF%87%E5%A4%9A%E6%95%B0%E6%8D%AE%E9%87%8F%E3%80%82"><span class="toc-number">25.</span> <span class="toc-text">25、尽量避免向客户端返回过多数据量。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#26%E3%80%81%E5%BD%93%E5%9C%A8SQL%E8%AF%AD%E5%8F%A5%E4%B8%AD%E8%BF%9E%E6%8E%A5%E5%A4%9A%E4%B8%AA%E8%A1%A8%E6%97%B6-%E8%AF%B7%E4%BD%BF%E7%94%A8%E8%A1%A8%E7%9A%84%E5%88%AB%E5%90%8D%EF%BC%8C%E5%B9%B6%E6%8A%8A%E5%88%AB%E5%90%8D%E5%89%8D%E7%BC%80%E4%BA%8E%E6%AF%8F%E4%B8%80%E5%88%97%E4%B8%8A%EF%BC%8C%E8%BF%99%E6%A0%B7%E8%AF%AD%E4%B9%89%E6%9B%B4%E5%8A%A0%E6%B8%85%E6%99%B0%E3%80%82"><span class="toc-number">26.</span> <span class="toc-text">26、当在SQL语句中连接多个表时,请使用表的别名，并把别名前缀于每一列上，这样语义更加清晰。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#27%E3%80%81%E5%B0%BD%E5%8F%AF%E8%83%BD%E4%BD%BF%E7%94%A8varchar-nvarchar-%E4%BB%A3%E6%9B%BF-char-nchar%E3%80%82"><span class="toc-number">27.</span> <span class="toc-text">27、尽可能使用varchar&#x2F;nvarchar 代替 char&#x2F;nchar。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#28%E3%80%81%E4%B8%BA%E4%BA%86%E6%8F%90%E9%AB%98group-by-%E8%AF%AD%E5%8F%A5%E7%9A%84%E6%95%88%E7%8E%87%EF%BC%8C%E5%8F%AF%E4%BB%A5%E5%9C%A8%E6%89%A7%E8%A1%8C%E5%88%B0%E8%AF%A5%E8%AF%AD%E5%8F%A5%E5%89%8D%EF%BC%8C%E6%8A%8A%E4%B8%8D%E9%9C%80%E8%A6%81%E7%9A%84%E8%AE%B0%E5%BD%95%E8%BF%87%E6%BB%A4%E6%8E%89%E3%80%82"><span class="toc-number">28.</span> <span class="toc-text">28、为了提高group by 语句的效率，可以在执行到该语句前，把不需要的记录过滤掉。</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#29%E3%80%81%E5%A6%82%E4%BD%95%E5%AD%97%E6%AE%B5%E7%B1%BB%E5%9E%8B%E6%98%AF%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%8Cwhere%E6%97%B6%E4%B8%80%E5%AE%9A%E7%94%A8%E5%BC%95%E5%8F%B7%E6%8B%AC%E8%B5%B7%E6%9D%A5%EF%BC%8C%E5%90%A6%E5%88%99%E7%B4%A2%E5%BC%95%E5%A4%B1%E6%95%88"><span class="toc-number">29.</span> <span class="toc-text">29、如何字段类型是字符串，where时一定用引号括起来，否则索引失效</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#30%E3%80%81%E4%BD%BF%E7%94%A8explain-%E5%88%86%E6%9E%90%E4%BD%A0SQL%E7%9A%84%E8%AE%A1%E5%88%92"><span class="toc-number">30.</span> <span class="toc-text">30、使用explain 分析你SQL的计划</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/02/08/Hexo%E6%96%B0%E5%BB%BA%E7%AC%AC%E4%B8%80%E7%AF%87%E5%8D%9A%E6%96%87/" title="Hexo新建第一篇博文"><img src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg1.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Hexo新建第一篇博文"/></a><div class="content"><a class="title" href="/2022/02/08/Hexo%E6%96%B0%E5%BB%BA%E7%AC%AC%E4%B8%80%E7%AF%87%E5%8D%9A%E6%96%87/" title="Hexo新建第一篇博文">Hexo新建第一篇博文</a><time datetime="2022-02-07T16:00:00.000Z" title="发表于 2022-02-08 00:00:00">2022-02-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/06/1681-%E6%9C%80%E5%B0%8F%E4%B8%8D%E5%85%BC%E5%AE%B9%E6%80%A7/" title="最小不兼容性"><img src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg7.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="最小不兼容性"/></a><div class="content"><a class="title" href="/2021/12/06/1681-%E6%9C%80%E5%B0%8F%E4%B8%8D%E5%85%BC%E5%AE%B9%E6%80%A7/" title="最小不兼容性">最小不兼容性</a><time datetime="2021-12-05T16:00:00.000Z" title="发表于 2021-12-06 00:00:00">2021-12-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/12/17/714-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA%E5%90%AB%E6%89%8B%E7%BB%AD%E8%B4%B9/" title="买卖股票的最佳时机含手续费"><img src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg20.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="买卖股票的最佳时机含手续费"/></a><div class="content"><a class="title" href="/2020/12/17/714-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA%E5%90%AB%E6%89%8B%E7%BB%AD%E8%B4%B9/" title="买卖股票的最佳时机含手续费">买卖股票的最佳时机含手续费</a><time datetime="2020-12-16T16:00:00.000Z" title="发表于 2020-12-17 00:00:00">2020-12-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/12/15/AOP/" title="AOP学习"><img src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg10.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="AOP学习"/></a><div class="content"><a class="title" href="/2020/12/15/AOP/" title="AOP学习">AOP学习</a><time datetime="2020-12-14T16:00:00.000Z" title="发表于 2020-12-15 00:00:00">2020-12-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/12/15/docker%E5%91%BD%E4%BB%A4/" title="docker命令"><img src="https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg16.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="docker命令"/></a><div class="content"><a class="title" href="/2020/12/15/docker%E5%91%BD%E4%BB%A4/" title="docker命令">docker命令</a><time datetime="2020-12-14T16:00:00.000Z" title="发表于 2020-12-15 00:00:00">2020-12-15</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://cdn.jsdelivr.net/gh/FantasticCode2019/cdn/backgroud/bg13.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2022 By FantasticCode</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my <a href="https://yyj_challenged.gitee.io//">blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page@5/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script><script src="/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'ea007ab939d0b7d664ea',
      clientSecret: '7f9f6bf9d107c6b3f99a5fe05e343ddd631adf82',
      repo: 'yyj_challenged',
      owner: 'FantasticCode2019',
      admin: ['FantasticCode2019'],
      id: '34802b28c8b4dc4301038b5a77cf5d94',
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !true) {
  if (true) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>